package com.cmcc.cmii.smsim.utils.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.*;

/**
 * @author Thanks
 */
public class JwtUtil {

    private static final String SECRET = "4a384baf300b4d13bd724cc17de0a64d";

    /**
     * 创建一个TOKEN
     * */
    public static JwtTokenResult createToken(Long userId){
        try {
            Algorithm algorithm = Algorithm.HMAC512(SECRET);
            Map<String, Object> map = new HashMap<String, Object>();

            Date nowDate = new Date();
            Calendar cal = new GregorianCalendar();
            cal.setTime(nowDate);
            cal.add(Calendar.HOUR_OF_DAY, 2);
            Date expireDate = cal.getTime();

            map.put("alg", "HS512");
            map.put("typ", "JWT");

            String token = JWT.create()
                    .withHeader(map)
                    .withClaim("uid", userId)
                    .withIssuer("CmiiIMServer")
                    .withSubject("CmiiIM_AccessToken")
                    .withAudience("CmiiIM")
                    .withIssuedAt(nowDate)
                    .withExpiresAt(expireDate)
                    .sign(algorithm);
            return new JwtTokenResult(token);

        } catch (JWTCreationException exception){
            exception.printStackTrace();
        }
        return new JwtTokenResult(null);
    }

    /**
     * 解析Token
     * */
    public static JwtVertifyResult verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("CmiiIMServer")
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            Claim claim = claims.get("uid");
            if (claim != null) {
                return new JwtVertifyResult(claim.asLong());
            }
        } catch (JWTVerificationException exception) {
            return JwtVertifyResult.result(exception.getMessage());
        }
        return JwtVertifyResult.NotVertified;
    }

    public static void main(String[] args) {
        JwtTokenResult token = createToken(100L);
        System.out.println(token);
        JwtVertifyResult jwtVertifyResult = verifyToken(token.getToken());
        /*String t = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1aWQiOiI4NDM5NjgiLCJzdWIiOiJDbWlpSU1fQWNjZXNzVG9rZW4iLCJhdWQiOiJDbWlpSU0iLCJpc3MiOiJDbWlpSU1TZXJ2ZXIiLCJleHAiOjE1OTA0MjM1MTgsImlhdCI6MTU5MDQxNjMxOH0.OVgPTN2ylIDfKQuTWQELGw0dDzN5LeejV-bSxJ9WfcJS6NCTe17QS_DwmOgvQqRjAAg668gBdJ8p_SAhFmau8Q";
        JwtVertifyResult jwtVertifyResult = verifyToken(t);*/
        Long userId = jwtVertifyResult.getUserId();
        System.out.println(userId);
    }
}
